package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.model.admin.vo.BaseRespVo;
import com.cskaoyan.model.admin.vo.WxOrderGoodsVo;
import com.cskaoyan.model.vx.bo.WxOrderCommentBo;
import com.cskaoyan.model.vx.vo.WxOrderDetailVo;
import com.cskaoyan.utils.TextAndHandOnWxOrListVoUtil;
import com.cskaoyan.model.admin.bo.ListBo;
import com.cskaoyan.model.admin.vo.AdBaseData;
import com.cskaoyan.model.vx.vo.WxOrderListVo;
import com.cskaoyan.utils.BaseDataOnListUtil;
import com.cskaoyan.utils.TextAndHandOnWxOrderDetailVoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @description: TODO
 * @author: jiaolei
 * @date: 2021/12/2 15:59
 */
@Service
@Transactional
public class WxOrderServiceImpl implements WxOrderService {
    @Autowired
    MarketOrderMapper marketOrderMapper;
    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Override
    public AdBaseData list(ListBo listBo, Short showType,Integer userId) {
        //session未获取
//        List<WxOrderListVo> wxOrderListVoList = new ArrayList<WxOrderListVo>();new
        MarketOrderExample marketOrderExample = new MarketOrderExample();

        MarketOrderExample.Criteria criteria=marketOrderExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        if(showType!=0){
            short showTypeToStatus=(short)(showType*100+1);
            criteria.andOrderStatusEqualTo(showTypeToStatus);
        }
        marketOrderExample.setOrderByClause("id"+" "+"desc");
        List<WxOrderListVo> wxOrderListVoList=marketOrderMapper.selectByExampleWOL(marketOrderExample);
        List<WxOrderListVo> wxOrderListVos = new ArrayList<>();

        for (WxOrderListVo wxOrderListVo : wxOrderListVoList) {
            if(wxOrderListVo.getDeleted()==1){
                continue;
            }

            wxOrderListVo.setOrderStatusText(TextAndHandOnWxOrListVoUtil.to(wxOrderListVo));

            MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
            marketOrderGoodsExample.createCriteria().andOrderIdEqualTo(wxOrderListVo.getId());
            List<WxOrderListVo.GoodsListBean> list1=marketOrderGoodsMapper.selectByExample2(marketOrderGoodsExample);
            wxOrderListVo.setGoodsList(list1);
            wxOrderListVos.add(wxOrderListVo);

        }
        return BaseDataOnListUtil.getAdBaseData(listBo,wxOrderListVos);
    }

    @Override
    public WxOrderDetailVo detail(Integer orderId) {
        //userId用来验证，不做也可
        //expressInfo未理解,需要类型肯数据库对应字段
        WxOrderDetailVo.OrderInfoBean orderInfoBean=marketOrderMapper.selectByPrimaryKey2(orderId);
        orderInfoBean.setOrderStatusText(TextAndHandOnWxOrderDetailVoUtil.to(orderInfoBean));

        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        List<WxOrderDetailVo.OrderGoodsBean> list=marketOrderGoodsMapper.selectByExample3(marketOrderGoodsExample);

        WxOrderDetailVo wxOrderDetailVo = new WxOrderDetailVo();
        wxOrderDetailVo.setOrderGoods(list);
        wxOrderDetailVo.setOrderInfo(orderInfoBean);
        return wxOrderDetailVo;
    }

    @Override
    public int cancel(Integer orderId,Integer userId) {
//        MarketOrder marketOrder = new MarketOrder();
//        marketOrder.setId(orderId);
//        marketOrder.setUserId(userId);
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        marketOrder.setOrderStatus((short)103);
        marketOrder.setUserId(userId);

        int i = marketOrderMapper.updateByPrimaryKey(marketOrder);
        return i;
    }

    @Override
    public int delete(Integer orderId) {
        int rows=marketOrderMapper.updateDeleted(orderId);
        return rows;
    }

    @Override
    public int comment(WxOrderCommentBo wxOrderCommentBo) {
//        int goodsId = marketOrderGoodsMapper.selectGoodsIdByPrimaryKey(wxOrderCommentBo.getOrderGoodsId());
        //localhost相比老师少一个orderGoodsId参数
        int goodsId = marketOrderMapper.selectGoodsIdByprimaryKey2(wxOrderCommentBo.getOrderGoodsId());
        wxOrderCommentBo.setValueId(goodsId);
        int rows=marketCommentMapper.insertSelective2(wxOrderCommentBo);
        return rows;
    }

    @Override
    public Integer refund(Integer orderId) {

        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        marketOrder.setOrderStatus((short)202);

        int i = marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
        return i;
    }

    @Override
    public Integer confirm(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        marketOrder.setOrderStatus((short)401);

        int i = marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
        return i;
    }

    @Override
    public WxOrderGoodsVo goods(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);
        WxOrderGoodsVo wxOrderGoodsVo=marketOrderGoodsMapper.selectByExample4(marketOrderGoodsExample);
        return wxOrderGoodsVo;
    }


    @Override
    public Map wxOrderSubmit(Integer addressId, Integer cartId, Integer couponId, String message, Integer userCouponId, Integer userId) {
        //返回的map
        Map<String, Integer> mapRespVO = new HashMap<>();

        //获取插入的order
        MarketOrder record = new MarketOrder();

        //给record中的address赋值
        MarketAddressExample marketAddressExample = new MarketAddressExample();
        marketAddressExample.createCriteria().andUserIdEqualTo(userId).andIdEqualTo(addressId);
        List<MarketAddress> marketAddresses = marketAddressMapper.selectByExample(marketAddressExample);
        if(marketAddresses.size() == 0){
            return mapRespVO;
        }
        MarketAddress marketAddress = marketAddresses.get(0);
        record.setConsignee(marketAddress.getName());
        record.setMobile(marketAddress.getTel());
        record.setAddress(marketAddress.getProvince()+marketAddress.getCity()+marketAddress.getCounty()+marketAddress.getAddressDetail());

        //给record中的留言,用户id,订单状态,订单编号,配送费赋值
        record.setMessage(message);
        record.setUserId(userId);
        record.setOrderStatus((short)101);
        record.setOrderSn(UUID.randomUUID()+"");
        record.setFreightPrice(new BigDecimal(0));
        record.setIntegralPrice(new BigDecimal(0));
        record.setGrouponPrice(new BigDecimal(0));
        record.setUpdateTime(new Date());
        record.setAddTime(new Date());
        record.setPayId(UUID.randomUUID()+"");
        record.setPayTime(new Date());


        //查询优惠卷
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
        if(marketCoupon != null){
            record.setCouponPrice(marketCoupon.getDiscount());
        }else {
            marketCoupon = new MarketCoupon();
            marketCoupon.setDiscount(new BigDecimal(0));
            record.setCouponPrice(marketCoupon.getDiscount());
        }


        //查询购物车,赋值商品总价格
        List<MarketCart> marketCarts;

        if (cartId ==0){
            MarketCartExample marketCartExample = new MarketCartExample();
            marketCartExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false).andCheckedEqualTo(true);
            marketCarts= marketCartMapper.selectByExample(marketCartExample);
        }else {
            MarketCart marketCart;
            marketCart= marketCartMapper.selectByPrimaryKey(cartId);
            marketCarts = new ArrayList<MarketCart>();
            marketCarts.add(marketCart);
        }

        BigDecimal goodsPrice = new BigDecimal(0);
        for (MarketCart cart : marketCarts) {
            BigDecimal multiply = cart.getPrice().multiply(new BigDecimal(cart.getNumber()));
            goodsPrice = goodsPrice.add(multiply);
        }
        record.setGoodsPrice(goodsPrice);



        //给订单费用和实付费赋值
        BigDecimal orderPrice= record.getFreightPrice().add(record.getGoodsPrice()).subtract(record.getCouponPrice());
        record.setOrderPrice(orderPrice);
        record.setActualPrice(orderPrice);

        //开始插入订单
        marketOrderMapper.insertSelective(record);

        //给返回的map赋值
        mapRespVO.put("grouponLinkId",0);
        mapRespVO.put("orderId",record.getId());


        //插入order_goods
        for (MarketCart marketCart : marketCarts) {
            MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
            marketOrderGoods.setOrderId(record.getId());
            marketOrderGoods.setGoodsId(marketCart.getGoodsId());
            marketOrderGoods.setGoodsName(marketCart.getGoodsName());
            marketOrderGoods.setGoodsSn(marketCart.getGoodsSn());
            marketOrderGoods.setProductId(marketCart.getProductId());
            marketOrderGoods.setNumber(marketCart.getNumber());
            marketOrderGoods.setPrice(marketCart.getPrice());
            marketOrderGoods.setSpecifications(marketCart.getSpecifications());
            marketOrderGoods.setPicUrl(marketCart.getPicUrl());
            marketOrderGoods.setUpdateTime(new Date());
            marketOrderGoods.setAddTime(new Date());
            marketOrderGoodsMapper.insertSelective(marketOrderGoods);
        }


        //将购物车中的信息给删除
        ArrayList<Integer> cartIds = new ArrayList<>();
        if(cartId == 0){
            for (MarketCart marketCart : marketCarts) {
                cartIds.add(marketCart.getId());
            }

        }else {
            cartIds.add(cartId);
        }
        for (Integer cartIdUpdate : cartIds) {
            MarketCartExample marketCartExample = new MarketCartExample();
            marketCartExample.createCriteria().andUserIdEqualTo(userId).andIdEqualTo(cartIdUpdate);
            MarketCart marketCartRecord = new MarketCart();
            marketCartRecord.setDeleted(true);
            marketCartMapper.updateByExampleSelective(marketCartRecord,marketCartExample);
        }


        return mapRespVO;
    }

    @Override
    public void updateStatus(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setDeleted(false);
        marketOrder.setUpdateTime(new Date());
        marketOrder.setOrderStatus((short) 301);
        marketOrder.setPayTime(new Date());
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }
}
